package com.leetcode.fenzhi;

/**
 * 爱吃香蕉的珂珂
 */
public class Solution875 {
    public int minEatingSpeed(int[] piles, int h) {
        if (piles == null || piles.length == 0) {
            return 0;
        }

        int left = 0;
        int right = (int)Math.pow(10, 13);
        int mid;
        int tmp;

        while (left <= right) {
            mid = left + (right - left) / 2;
            tmp = count(piles, mid, h);
            if (tmp == 0) {
                right = mid - 1;
            } else if (tmp == -1) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return right + 1;
    }

    private int count(int[] piles, int peed, int target) {
        if (piles == null || piles.length == 0) {
            return -2;
        }

        int result = 0;
        for (int pile : piles) {
            result += (pile + peed - 1) / peed;
        }

        if (result == target) {
            return 0;
        } else if (result < target) {
            return 1;
        } else {
            return -1;
        }
    }
}
